import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;

public class PercolationStats {
    // 接收trials入参
    private int trialCount;
    // 存储每次trial时opensite占所有site的比例
    private double[] trialResult;

    // perform independent trials on an n-by-n grid
    public PercolationStats(int n, int trials) {
        if (n <= 0 || trials <= 0) {
            throw new IllegalArgumentException("N and T must be <= 0");
        }
        trialResult = new double[trials];
        // 把入参放入成员变量里
        trialCount = trials;
        for (int trial = 0; trial < trialCount; trial++) {
            Percolation percolation = new Percolation(n);
            while (!percolation.percolates()) {
                int row = StdRandom.uniform(1, n + 1);
                int col = StdRandom.uniform(1, n + 1);
                percolation.open(row, col);
            }
            // 计算每一次的opensite占所有site的比例，放入result数组中
            double result = (double) percolation.numberOfOpenSites() / (n * n);
            trialResult[trial] = result;
        }
    }

    // sample mean of percolation threshold
    public double mean() {
        return StdStats.mean(trialResult);
    }

    // sample standard deviation of percolation threshold
    public double stddev() {
        return StdStats.stddev(trialResult);
    }

    // low endpoint of 95% confidence interval
    public double confidenceLo() {
        return mean() - ((1.96 * stddev()) / Math.sqrt(trialCount));
    }

    // high endpoint of 95% confidence interval
    public double confidenceHi() {
        return mean() + ((1.96 * stddev()) / Math.sqrt(trialCount));
    }

   // test client (see below)
   public static void main(String[] args) {
       int gridSize = 400;
       int trialCount = 100;
       if (args.length >= 2) {
           gridSize = Integer.parseInt(args[0]);
           trialCount = Integer.parseInt(args[1]);
       }
       PercolationStats ps = new PercolationStats(gridSize, trialCount);

       String confidence = ps.confidenceLo() + ", " + ps.confidenceHi();
       StdOut.println("mean                    = " + ps.mean());
       StdOut.println("stddev                  = " + ps.stddev());
       StdOut.println("95% confidence interval = " + confidence);
   }
}